package com.lq.util.jdbc;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.net.Socket;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;

import org.apache.commons.collections.map.ListOrderedMap;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mchange.v2.c3p0.ComboPooledDataSource;


/**
 * JDBC工厂<br>
 * @author 吃人的肉
 * QQ:376870344<br>
 * email:liuqingrou@163.com
 */
public class Jdbc{
	
	public static String defaultName = "default";

	protected static Logger log = Logger.getLogger(Jdbc.class);
	
	/**
	 * 是否需要properties配制文件
	 */
	public static boolean JDBC_NO_PROPERTIES=false;
	/**
	 * 是否开户寄生模式
	 */
	public static boolean PARASITIC_MODE=false;
	
	public static LqOCon oCon=null;
	
	public static Map<String,Map> propsDSMap=new HashMap();
	
	protected static Map<String,ComboPooledDataSource> dsWebgames = new HashMap<String, ComboPooledDataSource>();
	
	protected static LqConfig conf = null;
	
	private Jdbc(){}
	
	/**
	 * 已LqJdbc为主，将池提交给spring
	 * @return
	 */
	public static ComboPooledDataSource getCPDS() {
		return getSDWebgame(defaultName);
	}
	
	public static Map getPropsDSMap(String dsName) {
		if(propsDSMap.get(defaultName)==null) {
			if (JDBC_NO_PROPERTIES==false) {
				if (conf == null) {
					conf = new LqConfig();
					propsDSMap=conf.getDataSourceNameMap();
				}
			}
		}
		if(dsName==null) {
			return propsDSMap.get(defaultName);
		}else {
			return propsDSMap.get(dsName);
		}
	}
	
	public static ComboPooledDataSource getSDWebgame(String dsName) {
		if(dsName==null) {
			if (dsWebgames.get(defaultName)==null) {
				dsWebgames.put(defaultName,LqDBOperator.config(getPropsDSMap(null)));
			}
			return dsWebgames.get(defaultName);
		}else {
			if (dsWebgames.get(dsName)==null) {
				dsWebgames.put(dsName,LqDBOperator.config(getPropsDSMap(dsName)));
			}
			return dsWebgames.get(dsName);
		}
	}
	
	/**
	 * 得到一个数据源《单独使用需要关闭，掉用close();》
	 * @param dsName
	 * @return
	 */
	public static LqJdbcFactory getDS(String dsName){
		LqJdbcFactory jdbc = null;
		try {
			LqDBConfig dBConfig = getDBConfig(getPropsDSMap(dsName));
			jdbc = new LqJdbcFactory(getSDWebgame(dsName).getConnection(),dBConfig);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("LqJdbc",e);
			e.printStackTrace();
		}
		return jdbc;
	}
	
	/**
	 * 得数据配置信息
	 * @param map
	 * @return
	 */
	public static LqDBConfig getDBConfig(Map map) {
		LqDBConfig dBConfig = new LqDBConfig();
		dBConfig.setUrl(map.get("url").toString());
		dBConfig.setUsername(map.get("username").toString());
		dBConfig.setPwd(map.get("pwd").toString());
		dBConfig.setDriverClassName(map.get("DriverClassName").toString());
		dBConfig.setSqlSuccessTime("false");
		if(map.get("SqlSuccessTime")!=null) {
			dBConfig.setSqlSuccessTime(map.get("SqlSuccessTime").toString());
		}
		dBConfig.setSqlLog("false");
		if(map.get("SqlLog")!=null) {
			dBConfig.setSqlLog(map.get("SqlLog").toString());
		}
		return dBConfig;
	}
	
	
	/**
	 * 数据库语句分类--SQL
	 * @param databasesSelectInterface
	 * @return
	 */
	public static String sql(DatabasesInterface databasesSelectInterface){
		LqDBConfig c = getDBConfig(getPropsDSMap(null));
		if (c.getDriverClassName().equalsIgnoreCase("com.microsoft.sqlserver.jdbc.SQLServerDriver")) {
        	//SQL SERVER
			return databasesSelectInterface.sqlserver();
		}else if(c.getDriverClassName().toLowerCase().indexOf("com.mysql")!=-1){
			//MY SQL
			return databasesSelectInterface.mysql();
		}else if(c.getDriverClassName().toLowerCase().indexOf("postgresql")!=-1){
			//postgresql
			return databasesSelectInterface.postgresql();
		}else if(c.getDriverClassName().equalsIgnoreCase("oracle.jdbc.driver.OracleDriver")){
			//Oracle
			return databasesSelectInterface.oracle();
		}else if(c.getDriverClassName().equalsIgnoreCase("org.sqlite.JDBC")){
			//SqlLite
			return databasesSelectInterface.sqlLite();
		}
		return null;
	}
	
	/**
	 * 数据库语句分类--SQL
	 * @param databasesSelectInterface
	 * @return
	 */
	public static String sql(DatabasesAbstract databasesAbstract){
		LqDBConfig c = getDBConfig(getPropsDSMap(null));
		if (c.getDriverClassName().equalsIgnoreCase("com.microsoft.sqlserver.jdbc.SQLServerDriver")) {
        	//SQL SERVER
			return databasesAbstract.sqlserver();
		}else if(c.getDriverClassName().toLowerCase().indexOf("com.mysql")!=-1){
			//MY SQL
			return databasesAbstract.mysql();
		}else if(c.getDriverClassName().toLowerCase().indexOf("postgresql")!=-1){
			//postgresql
			return databasesAbstract.postgresql();
		}else if(c.getDriverClassName().equalsIgnoreCase("oracle.jdbc.driver.OracleDriver")){
			//Oracle
			return databasesAbstract.oracle();
		}else if(c.getDriverClassName().equalsIgnoreCase("org.sqlite.JDBC")){
			//SqlLite
			return databasesAbstract.sqlLite();
		}else if(c.getDriverClassName().equalsIgnoreCase("net.ucanaccess.jdbc.UcanaccessDriver")){
			//Access
			return databasesAbstract.access();
		}
		return null;
	}
	
	/**
	 * 数据库语句分类--SQL
	 * @param databasesSelectInterface
	 * @return
	 */
	public static Object sql(DatabasesInterfaceForObject databasesInterfaceForObject){
		LqDBConfig c = getDBConfig(getPropsDSMap(null));
		if (c.getDriverClassName().equalsIgnoreCase("com.microsoft.sqlserver.jdbc.SQLServerDriver")) {
        	//SQL SERVER
			return databasesInterfaceForObject.sqlserver();
		}else if(c.getDriverClassName().toLowerCase().indexOf("com.mysql")!=-1){
			//MY SQL
			return databasesInterfaceForObject.mysql();
		}else if(c.getDriverClassName().toLowerCase().indexOf("postgresql")!=-1){
			//postgresql
			return databasesInterfaceForObject.postgresql();
		}else if(c.getDriverClassName().equalsIgnoreCase("oracle.jdbc.driver.OracleDriver")){
			//Oracle
			return databasesInterfaceForObject.oracle();
		}else if(c.getDriverClassName().equalsIgnoreCase("org.sqlite.JDBC")){
			//SqlLite
			return databasesInterfaceForObject.sqlLite();
		}
		return null;
	}
	/**
	 * 数据库语句分类--SQL
	 * @param databasesSelectInterface
	 * @return
	 */
	public static Object sql(DatabasesAbstractForObject databasesAbstractForObject){
		LqDBConfig c = getDBConfig(getPropsDSMap(null));
		if (c.getDriverClassName().equalsIgnoreCase("com.microsoft.sqlserver.jdbc.SQLServerDriver")) {
			//SQL SERVER
			return databasesAbstractForObject.sqlserver();
		}else if(c.getDriverClassName().toLowerCase().indexOf("com.mysql")!=-1){
			//MY SQL
			return databasesAbstractForObject.mysql();
		}else if(c.getDriverClassName().toLowerCase().indexOf("postgresql")!=-1){
			//postgresql
			return databasesAbstractForObject.postgresql();
		}else if(c.getDriverClassName().equalsIgnoreCase("oracle.jdbc.driver.OracleDriver")){
			//Oracle
			return databasesAbstractForObject.oracle();
		}else if(c.getDriverClassName().equalsIgnoreCase("org.sqlite.JDBC")){
			//SqlLite
			return databasesAbstractForObject.sqlLite();
		}else if(c.getDriverClassName().equalsIgnoreCase("net.ucanaccess.jdbc.UcanaccessDriver")){
			//Access
			return databasesAbstractForObject.access();
		}
		return null;
	}
	
	/**
	 * 数据库语句分类--SQL
	 * @param databasesSelectInterface
	 * @return
	 */
	public static String sql(String dsName,DatabasesInterface databasesSelectInterface){
		if (dsName==null) {
			//抛异常
			StringBuffer eStringBuffer=new StringBuffer();
			eStringBuffer.append("数据源名称不能为NULL！！");
			try {
				throw new LqJdbcException(eStringBuffer.toString());
			} catch (LqJdbcException e) {
				log.error("LqJdbc",e);
				e.printStackTrace();
			}
		}else{
			ComboPooledDataSource dbo=getSDWebgame(dsName);
			if (dbo==null) {
				//抛异常
				StringBuffer eStringBuffer=new StringBuffer();
				eStringBuffer.append("这个《").append(dsName).append("》数据源不存在！！");
				try {
					throw new LqJdbcException(eStringBuffer.toString());
				} catch (LqJdbcException e) {
					log.error("LqJdbc",e);
					e.printStackTrace();
				}
			}else{
				if (dbo.getDriverClass().equalsIgnoreCase("com.microsoft.sqlserver.jdbc.SQLServerDriver")) {
					//SQL SERVER
					return databasesSelectInterface.sqlserver();
				}else if(dbo.getDriverClass().toLowerCase().indexOf("postgresql")!=-1){
					//postgresql
					return databasesSelectInterface.postgresql();
				}else if(dbo.getDriverClass().toLowerCase().toLowerCase().indexOf("com.mysql")!=-1){
					//MY SQL
					return databasesSelectInterface.mysql();
				}else if(dbo.getDriverClass().equalsIgnoreCase("oracle.jdbc.driver.OracleDriver")){
					//Oracle
					return databasesSelectInterface.oracle();
				}else if(dbo.getDriverClass().equalsIgnoreCase("org.sqlite.JDBC")){
					//SqlLite
					return databasesSelectInterface.sqlLite();
				}
			}
		}
		return null;
	}
	/**
	 * 数据库语句分类--SQL
	 * @param databasesSelectInterface
	 * @return
	 */
	public static String sql(String dsName,DatabasesAbstract databasesAbstract){
		if (dsName==null) {
			//抛异常
			StringBuffer eStringBuffer=new StringBuffer();
			eStringBuffer.append("数据源名称不能为NULL！！");
			try {
				throw new LqJdbcException(eStringBuffer.toString());
			} catch (LqJdbcException e) {
				log.error("LqJdbc",e);
				e.printStackTrace();
			}
		}else{
			ComboPooledDataSource dbo=getSDWebgame(dsName);
			if (dbo==null) {
				//抛异常
				StringBuffer eStringBuffer=new StringBuffer();
				eStringBuffer.append("这个《").append(dsName).append("》数据源不存在！！");
				try {
					throw new LqJdbcException(eStringBuffer.toString());
				} catch (LqJdbcException e) {
					log.error("LqJdbc",e);
					e.printStackTrace();
				}
			}else{
				if (dbo.getDriverClass().equalsIgnoreCase("com.microsoft.sqlserver.jdbc.SQLServerDriver")) {
					//SQL SERVER
					return databasesAbstract.sqlserver();
				}else if(dbo.getDriverClass().toLowerCase().indexOf("postgresql")!=-1){
					//postgresql
					return databasesAbstract.postgresql();
				}else if(dbo.getDriverClass().toLowerCase().toLowerCase().indexOf("com.mysql")!=-1){
					//MY SQL
					return databasesAbstract.mysql();
				}else if(dbo.getDriverClass().equalsIgnoreCase("oracle.jdbc.driver.OracleDriver")){
					//Oracle
					return databasesAbstract.oracle();
				}else if(dbo.getDriverClass().equalsIgnoreCase("org.sqlite.JDBC")){
					//SqlLite
					return databasesAbstract.sqlLite();
				}else if(dbo.getDriverClass().equalsIgnoreCase("net.ucanaccess.jdbc.UcanaccessDriver")){
					//Access
					return databasesAbstract.access();
				}
			}
		}
		return null;
	}
	
	/**
	 * 数据库语句分类--SQL
	 * @param databasesSelectInterface
	 * @return
	 */
	public static Object sql(String dsName,DatabasesInterfaceForObject databasesInterfaceForObject){
		if (dsName==null) {
			//抛异常
			StringBuffer eStringBuffer=new StringBuffer();
			eStringBuffer.append("数据源名称不能为NULL！！");
			try {
				throw new LqJdbcException(eStringBuffer.toString());
			} catch (LqJdbcException e) {
				log.error("LqJdbc",e);
				e.printStackTrace();
			}
		}else{
			ComboPooledDataSource dbo=getSDWebgame(dsName);
			if (dbo==null) {
				//抛异常
				StringBuffer eStringBuffer=new StringBuffer();
				eStringBuffer.append("这个《").append(dsName).append("》数据源不存在！！");
				try {
					throw new LqJdbcException(eStringBuffer.toString());
				} catch (LqJdbcException e) {
					log.error("LqJdbc",e);
					e.printStackTrace();
				}
			}else{
				if (dbo.getDriverClass().equalsIgnoreCase("com.microsoft.sqlserver.jdbc.SQLServerDriver")) {
					//SQL SERVER
					return databasesInterfaceForObject.sqlserver();
				}else if(dbo.getDriverClass().toLowerCase().indexOf("com.mysql")!=-1){
					//MY SQL
					return databasesInterfaceForObject.mysql();
				}else if(dbo.getDriverClass().toLowerCase().indexOf("postgresql")!=-1){
					//postgresql
					return databasesInterfaceForObject.postgresql();
				}else if(dbo.getDriverClass().equalsIgnoreCase("oracle.jdbc.driver.OracleDriver")){
					//Oracle
					return databasesInterfaceForObject.oracle();
				}else if(dbo.getDriverClass().equalsIgnoreCase("org.sqlite.JDBC")){
					//SqlLite
					return databasesInterfaceForObject.sqlLite();
				}
			}
		}
		return null;
	}
	/**
	 * 数据库语句分类--SQL
	 * @param databasesSelectInterface
	 * @return
	 */
	public static Object sql(String dsName,DatabasesAbstractForObject databasesAbstractForObject){
		if (dsName==null) {
			//抛异常
			StringBuffer eStringBuffer=new StringBuffer();
			eStringBuffer.append("数据源名称不能为NULL！！");
			try {
				throw new LqJdbcException(eStringBuffer.toString());
			} catch (LqJdbcException e) {
				log.error("LqJdbc",e);
				e.printStackTrace();
			}
		}else{
			ComboPooledDataSource dbo=getSDWebgame(dsName);
			if (dbo==null) {
				//抛异常
				StringBuffer eStringBuffer=new StringBuffer();
				eStringBuffer.append("这个《").append(dsName).append("》数据源不存在！！");
				try {
					throw new LqJdbcException(eStringBuffer.toString());
				} catch (LqJdbcException e) {
					log.error("LqJdbc",e);
					e.printStackTrace();
				}
			}else{
				if (dbo.getDriverClass().equalsIgnoreCase("com.microsoft.sqlserver.jdbc.SQLServerDriver")) {
					//SQL SERVER
					return databasesAbstractForObject.sqlserver();
				}else if(dbo.getDriverClass().toLowerCase().indexOf("com.mysql")!=-1){
					//MY SQL
					return databasesAbstractForObject.mysql();
				}else if(dbo.getDriverClass().toLowerCase().indexOf("postgresql")!=-1){
					//postgresql
					return databasesAbstractForObject.postgresql();
				}else if(dbo.getDriverClass().equalsIgnoreCase("oracle.jdbc.driver.OracleDriver")){
					//Oracle
					return databasesAbstractForObject.oracle();
				}else if(dbo.getDriverClass().equalsIgnoreCase("org.sqlite.JDBC")){
					//SqlLite
					return databasesAbstractForObject.sqlLite();
				}else if(dbo.getDriverClass().equalsIgnoreCase("net.ucanaccess.jdbc.UcanaccessDriver")){
					//Access
					return databasesAbstractForObject.access();
				}
			}
		}
		return null;
	}
	
	/**
	 * 总链接数
	 * @return
	 */
	public static long getNumConnectionsDefaultUser(){
		return getNumConnectionsDefaultUser(null);
	}
	
	/**
	 * 总链接数
	 * @return
	 */
	public static long getNumConnectionsDefaultUser(String dsName){
		try {
			return getSDWebgame(dsName).getNumConnectionsDefaultUser();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("LqJdbc",e);
			e.printStackTrace();
		}
		return 0;
	}
	
	
	/**
	 * 正在运行状态的连接数
	 * @return
	 */
	public static long getNumBusyConnectionsDefaultUser(){
		return getNumBusyConnectionsDefaultUser(null);
	}
	
	/**
	 * 正在运行状态的连接数
	 * @return
	 */
	public static long getNumBusyConnectionsDefaultUser(String dsName){
		try {
			return getSDWebgame(dsName).getNumBusyConnectionsDefaultUser();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("LqJdbc",e);
			e.printStackTrace();
		}
		return 0;
	}
	
	
	
	/**
	 * 空闲连接数
	 * @return
	 */
	public static long getNumIdleConnectionsDefaultUser(){
		return getNumIdleConnectionsDefaultUser(null);
	}
	
	/**
	 * 空闲连接数
	 * @return
	 */
	public static long getNumIdleConnectionsDefaultUser(String dsName){
		try {
			return getSDWebgame(dsName).getNumBusyConnectionsDefaultUser();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("LqJdbc",e);
			e.printStackTrace();
		}
		return 0;
	}
	
	/**
	 * 寄生模式使用，从对方连接池获取连接
	 * @return
	 */
	public static Connection getOCon() {
		return oCon.getCon();
	}
	
	
	public static Connection getCon(){
		try {
			Connection con=null;
			if (PARASITIC_MODE) {
				con=getOCon();
			}else {
				con=getSDWebgame(defaultName).getConnection();
			}
			return con;
		} catch (Exception e) {
			log.error("LqJdbc",e);
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 得到一个JDBC工厂，独立使用时，最后要CLOSE();
	 * @return
	 */
	public static LqJdbcFactory getFactory() {
		LqDBConfig dBConfig = getDBConfig(getPropsDSMap(null));
		LqJdbcFactory jdbc=new LqJdbcFactory(getCon(),dBConfig);
		return jdbc;
	}
	
	
	/**
	 * EXEC
	 * @param sql
	 * @return
	 */
	@Deprecated
	public static int execute(String sql){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.execute(sql,1,new Object[] {});
	}
	/**
	 * EXEC
	 * @param sql
	 * @return
	 */
	public static int execute(String sql,Object[] obj){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.execute(sql,1,obj);
	}
	public static int execute(String sql,Object obj){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.execute(sql,2,new Object[] {obj});
	}
	
	/**
	 * EXEC 插入并返回其自增ID《已测试mysql下支持高并发》
	 * @param sql
	 * @apiNote  因为LAST_INSERT_ID是基于Connection的，只要每个线程都使用独立的Connection对象，LAST_INSERT_ID函数 将返回该Connection对AUTO_INCREMENT列最新的insert or update*作生成的第一个record的ID。这个值不能被其它客户端（Connection）影响，保证了你能够找回自己的 ID 而不用担心其它客户端的活动，而且不需要加锁。使用单INSERT语句插入多条记录,  LAST_INSERT_ID返回一个列表。
	 * @return
	 */
	public static long insertAndReturnId(String sql,Object... obj){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.insertAndReturnId(sql,obj);
	}
	
	/**
	 * 分页
	 * @param sql
	 * @param pageNumber
	 * @param pageSize
	 * @param totalCount
	 * @return
	 */
	@Deprecated
	public static <T> Page<T> findPage(String sql,Integer pageNumber,Integer pageSize,Long totalCount,Class<T> cls){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.findPage(sql, pageNumber, pageSize, totalCount,cls);
	}
	/**
	 * 分页《安全》<br>
	 * SQL_SERVER_2005分页:SELECT ROW_NUMBER() OVER (ORDER BY id) AS RowNumber,* from tableName
	 * @param sql
	 * @param pageNumber1 当前页数
	 * @param pageSize 一页所显示的记录数
	 * @param totalCount 总记录数
	 * @return
	 */
	public static <T> Page<T> findPage(String sql,Integer pageNumber,Integer pageSize,Long totalCount,Class<T> cls,Object[] obj){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.findPage(sql, pageNumber, pageSize, totalCount,cls,obj);
	}
	public static <T> Page<T> findPage(String sql,Integer pageNumber,Integer pageSize,Long totalCount,Class<T> cls,Object obj){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.findPage(sql, pageNumber, pageSize, totalCount,cls,obj);
	}
	
	/**
	 * 分页《安全》<br>
	 * SQL_SERVER_2005分页:SELECT ROW_NUMBER() OVER (ORDER BY id) AS RowNumber,* from tableName
	 * @param <T>
	 * @param sql
	 * @param pageNumber1 当前页数
	 * @param pageSize 一页所显示的记录数
	 * @param sqlCount 得总记录数SQL
	 * @return
	 */
	public static <T> Page<T> findPage(String sql,Integer pageNumber,Integer pageSize,String sqlCount,Class<T> cls,Object[] obj){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.findPage(sql, pageNumber, pageSize, sqlCount,cls,obj);
	}
	public static <T> Page<T> findPage(String sql,Integer pageNumber,Integer pageSize,String sqlCount,Class<T> cls,Object obj){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.findPage(sql, pageNumber, pageSize, sqlCount,cls,obj);
	}
	
	@Deprecated
	public static <T> Page<T> findPage(String sql,Integer pageNumber,Integer pageSize,String sqlCount,Class<T> cls){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.findPage(sql, pageNumber, pageSize, sqlCount,cls);
	}
	
	
	/**
	 * 分页
	 * @param sql
	 * @param pageNumber
	 * @param pageSize
	 * @param totalCount
	 * @return
	 */
	@Deprecated
	public static Page<ListOrderedMap> findPage(String sql,Integer pageNumber,Integer pageSize,Long totalCount){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.findPage(sql, pageNumber, pageSize, totalCount);
	}
	@Deprecated
	public static Page<JSONObject> queryPageForJson(String sql,Integer pageNumber,Integer pageSize,Long totalCount){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.queryPageForJson(sql, pageNumber, pageSize, totalCount);
	}
	/**
	 * 分页《安全》<br>
	 * SQL_SERVER_2005分页:SELECT ROW_NUMBER() OVER (ORDER BY id) AS RowNumber,* from tableName
	 * @param sql
	 * @param pageNumber1 当前页数
	 * @param pageSize 一页所显示的记录数
	 * @param totalCount 总记录数
	 * @return
	 */
	public static Page<ListOrderedMap> findPage(String sql,Integer pageNumber,Integer pageSize,Long totalCount,Object[] obj){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.findPage(sql, pageNumber, pageSize, totalCount,obj);
	}
	public static Page<ListOrderedMap> findPage(String sql,Integer pageNumber,Integer pageSize,Long totalCount,Object obj){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.findPage(sql, pageNumber, pageSize, totalCount,obj);
	}
	public static Page<JSONObject> queryPageForJson(String sql,Integer pageNumber,Integer pageSize,Long totalCount,Object[] obj){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.queryPageForJson(sql, pageNumber, pageSize, totalCount,obj);
	}
	public static Page<JSONObject> queryPageForJson(String sql,Integer pageNumber,Integer pageSize,Long totalCount,Object obj){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.queryPageForJson(sql, pageNumber, pageSize, totalCount,obj);
	}
	
	/**
	 * 分页《安全》<br>
	 * SQL_SERVER_2005分页:SELECT ROW_NUMBER() OVER (ORDER BY id) AS RowNumber,* from tableName
	 * @param sql
	 * @param pageNumber1 当前页数
	 * @param pageSize 一页所显示的记录数
	 * @param sqlCount 得总记录数SQL
	 * @return
	 */
	
	public static Page<ListOrderedMap> findPage(String sql,Integer pageNumber,Integer pageSize,String sqlCount,Object[] obj){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.findPage(sql, pageNumber, pageSize, sqlCount,obj);
	}
	public static Page<ListOrderedMap> findPage(String sql,Integer pageNumber,Integer pageSize,String sqlCount,Object obj){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.findPage(sql, pageNumber, pageSize, sqlCount,obj);
	}
	public static Page<JSONObject> queryPageForJson(String sql,Integer pageNumber,Integer pageSize,String sqlCount,Object[] obj){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.queryPageForJson(sql, pageNumber, pageSize, sqlCount,obj);
	}
	public static Page<JSONObject> queryPageForJson(String sql,Integer pageNumber,Integer pageSize,String sqlCount,Object obj){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.queryPageForJson(sql, pageNumber, pageSize, sqlCount,obj);
	}
	
	@Deprecated
	public static Page<ListOrderedMap> findPage(String sql,Integer pageNumber,Integer pageSize,String sqlCount){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.findPage(sql, pageNumber, pageSize, sqlCount);
	}
	@Deprecated
	public static Page<JSONObject> queryPageForJson(String sql,Integer pageNumber,Integer pageSize,String sqlCount){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.queryPageForJson(sql, pageNumber, pageSize, sqlCount);
	}
	
	/**
	 * 查询
	 * @param sql
	 * @param cls
	 * @return
	 */
	@Deprecated
	public static <T> List<T> find(String sql,Class<T> cls){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.find(sql,cls,1,new Object[]{});
	}
	
	/**
	 * 查询
	 * @param sql
	 * @param cls
	 * @param obj    Object... obj
	 * @return
	 */
	public static <T> List<T> find(String sql,Class<T> cls,Object[] obj){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.find(sql,cls,1,obj);
	}
	
	/**
	 * 查询
	 * @param sql
	 * @return
	 */
	public static <T> List<T> find(String sql,Class<T> cls,Object t){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.find(sql,cls,2,new Object[]{t});
	}
	
	/**
	 * 查询
	 * @param sql
	 * @return
	 */
	@Deprecated
	public static List<ListOrderedMap> find(String sql){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.find(sql);
	}
	
	/**
	 * 查询
	 * @param sql
	 * @return
	 */
	public static List<ListOrderedMap> find(String sql,Object[] obj){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.find(sql, obj);
	}
	
	public static List<ListOrderedMap> find(String sql,Object obj){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.find(sql, obj);
	}
	
	
	@Deprecated
	public static JSONArray queryForJson(String sql){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.queryForJson(sql);
	}
	public static JSONArray queryForJson(String sql,Object[] obj){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.queryForJson(sql, obj);
	}
	public static JSONArray queryForJson(String sql,Object obj){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.queryForJson(sql, obj);
	}
	
	public static int save(Object obj){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.save(obj);
	}
	public static int update(Object obj){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.update(obj);
	}
	public static int delete(Object obj){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.delete(obj);
	}
	
	/**
	 * 操作结果集
	 * @param resultSet
	 */
	public static void operationResultSet(LqResultSet resultSet){
		LqJdbcFactory jdbc=getFactory();
		jdbc.operationResultSet(resultSet);
	}

	
	/**
	 * 事务操作
	 * @param shiWu
	 * @return
	 */
	public static int shiwu(LqShiWu shiWu){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.shiwu(shiWu);
	}
	
	/**
	 * 批量操作
	 * @param sql
	 * @param piLiang
	 * @return
	 */
	public static int[] piliang(String sql,LqPiLiang piLiang){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.piliang(sql, piLiang);
	}
	
	/**
	 * 批量操作
	 * @param sql
	 * @param piLiang
	 * @param auto   false:关闭事务，true:开启事务
	 * @return
	 */
	public static int[] piliang(String sql,LqPiLiang piLiang,boolean auto){
		LqJdbcFactory jdbc=getFactory();
		return jdbc.piliang(sql, piLiang,auto);
	}
	
	
	/**
     * 生成表对应实体类
     * @param path 实体类生成在哪个包下面   如:路径 com.lq.entity
     * @param tableName 表名
     * @param url 连接
     * @param driver 驱动名
     * @param privateKey 主键,无主键设成唯一标识符的字段
     */
    public static void createEntity(String path,String tableName,String url,String driver,String privateKey){
    	Connection con = getCon();
		if (con!=null) {
			try {
				con.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				log.error("LqJdbc",e);
				e.printStackTrace();
			}
		}
    	new LqGoEntity(path,tableName,url,driver,privateKey);
 		System.out.println("生成实体类成功!");
    }
    
    /**
     * 生成表对应实体类
     * @param path 实体类生成在哪个包下面   如:路径 com.lq.entity
     * @param tableName 表名
     * @param url 连接
     * @param driver 驱动名
     * @param privateKey 主键,无主键设成唯一标识符的字段
     * @param dynamicPath  动态包路径
     */
    public static void createEntity(String path,String tableName,String url,String driver,String privateKey,String dynamicPath){
    	Connection con = getCon();
		if (con!=null) {
			try {
				con.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				log.error("LqJdbc",e);
				e.printStackTrace();
			}
		}
    	new LqGoEntity(path,tableName,url,driver,privateKey,dynamicPath);
 		System.out.println("生成实体类成功!");
    }
    
    /**
     * 生成表对应实体类
     * @param path 实体类生成在哪个包下面   如:路径 com.lq.entity
     * @param tableName 表名
     * @param privateKey 主键,无主键设成唯一标识符的字段
     */
	public static void createEntity(String path, String tableName, String privateKey) {
		Connection con = getCon();
		if (con!=null) {
			try {
				con.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				log.error("LqJdbc",e);
				e.printStackTrace();
			}
		}
		new LqGoEntity(path, tableName, privateKey);
		System.out.println("生成实体类成功!");
	}

	
	/**
	 * 生成表对应实体类
	 * @param path 实体类生成在哪个包下面   如:路径 com.lq.entity
	 * @param tableName 表名
	 * @param privateKey 主键,无主键设成唯一标识符的字段
	 * @param dynamicPath 动态包路径
	 */
	public static void createEntity(String path, String tableName, String privateKey, String dynamicPath) {
		Connection con = getCon();
		if (con!=null) {
			try {
				con.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				log.error("LqJdbc",e);
				e.printStackTrace();
			}
		}
		new LqGoEntity(path, tableName, privateKey, dynamicPath);
		System.out.println("生成实体类成功!");
	}
	
	
   
   
   
	/**
	* 生成SQL语句
	* @param tableName 表名
	* @param privateKey 主键或是编号
	* @return 0:插入语句,1修改语句,2参数
	*/
	public static List<String> createSQL(String tableName,String url,String driver,String privateKey){
		Connection con = getCon();
		if (con!=null) {
			try {
				con.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				log.error("LqJdbc",e);
				e.printStackTrace();
			}
		}
		LqGoInsertAndUpdateAndSelect a=new LqGoInsertAndUpdateAndSelect(tableName,url,driver,privateKey);
		List<String> list=new ArrayList<String>();
		list.add(a.insertStr);
		list.add(a.insertObj);
		list.add(a.updateStr);
		list.add(a.updateObj);
		return list;
	}
	
	/**
	 * 生成SQL语句
	 * @param tableName 表名
	 * @param privateKey 主键或是编号
	 * @return 0:插入语句,1修改语句,2参数
	 */
	public static List<String> createSQL(String tableName,String privateKey){
		Connection con = getCon();
		if (con!=null) {
			try {
				con.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				log.error("LqJdbc",e);
				e.printStackTrace();
			}
		}
		LqGoInsertAndUpdateAndSelect a=new LqGoInsertAndUpdateAndSelect(tableName,privateKey);
		List<String> list=new ArrayList<String>();
		list.add(a.insertStr);
		list.add(a.insertStrKey);
		list.add(a.insertObj);
		list.add(a.updateStr);
		list.add(a.updateStrKey);
		list.add(a.updateObj);
		return list;
	}
	
	/**
	 * 配置类转Map
	 * @param config
	 * @return
	 */
	public static Map configToMap(LqDBConfig config) {
		Map propsMap=new HashMap();
		propsMap.put("DriverClassName", config.getDriverClassName());
		propsMap.put("pageSize", config.getPageSize());
		propsMap.put("groupPageSize", config.getGroupPageSize());
		propsMap.put("SqlLog", config.getSqlLog());
		propsMap.put("SqlSuccessTime", config.getSqlSuccessTime());
		propsMap.put("url", config.getUrl());
		propsMap.put("username", config.getUsername());
		propsMap.put("pwd", config.getPwd());
		propsMap.put("MaxPoolSize", config.getMaxPoolSize());
		propsMap.put("MinPoolSize", config.getMinPoolSize());
		propsMap.put("InitialPoolSize", config.getInitialPoolSize());
		propsMap.put("NumHelperThreads", config.getNumHelperThreads());
		propsMap.put("CheckoutTimeout", config.getCheckoutTimeout());
		return propsMap;
	}
	
	
	/**
	 * SQL渲染
	 * @param sql
	 * @param obj
	 * @return
	 */
	public static String sqlRender(String sql,Object obj) {
		if(obj instanceof HashMap) {
			Map<String,Object> map=(Map) obj;
			for (Map.Entry<String, Object> m : map.entrySet()) {
				if(m.getValue() instanceof Integer) {
					sql=sql.replace("${"+m.getKey()+"}", m.getValue()+"");
				}else {
					sql=sql.replace("${"+m.getKey()+"}", "'"+m.getValue()+"'");
				}
			}
		}else if(obj instanceof JSONObject) {
			JSONObject jsonObject=(JSONObject) obj;
			for(JSONObject.Entry<String, Object> m : jsonObject.entrySet()) {
				if(m.getValue() instanceof Integer) {
					sql=sql.replace("${"+m.getKey()+"}", m.getValue()+"");
				}else {
					sql=sql.replace("${"+m.getKey()+"}", "'"+m.getValue()+"'");
				}
			}
		}else {
			Class<? extends Object> cla=obj.getClass();
			for (int i = 0; i < cla.getDeclaredFields().length; i++) {
				Field f=cla.getDeclaredFields()[i];
				boolean flag = f.isAccessible();
				f.setAccessible(true);
				try {
					if(f.get(obj) instanceof Integer) {
						sql=sql.replace("${"+f.getName()+"}", f.get(obj)+"");
					}else {
						sql=sql.replace("${"+f.getName()+"}", "'"+f.get(obj)+"'");
					}
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					log.error("LqJdbc",e);
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					log.error("LqJdbc",e);
					e.printStackTrace();
				}
				f.setAccessible(flag);
			}
		}
		return sql;
	}
	
	/**
	 * SQL渲染
	 * @param sql
	 * @param obj
	 * @return
	 */
	public static String sqlRender(String sql,Object[] obj) {
		for (int k = 0; k < obj.length; k++) {
			if(obj[k] instanceof Integer) {
				sql=sql.replaceFirst("\\?", Matcher.quoteReplacement(obj[k]+""));
			}else {
				sql=sql.replaceFirst("\\?", Matcher.quoteReplacement("'"+obj[k]+"'"));
			}
		}
		return sql;
	}
	
	
	public static JSONArray query(String sql) {
        Socket socket = null;
        OutputStream os = null;
        PrintWriter pw = null;
        InputStream is = null;
        JSONObject obj = null;
        JSONArray j = null;
        BufferedReader br = null;
        try {
            // 和服务器创建连接
            socket = new Socket("127.0.0.1", 8099);
            // 要发送给服务器的信息
            os = socket.getOutputStream();
            pw = new PrintWriter(new OutputStreamWriter(os, "utf-8"));
            // 从服务器接收的信息
            sql = sql + " liuqing13934664424\r\n";
            pw.write(sql);
            pw.flush();
            is = socket.getInputStream();
            br = new BufferedReader(new InputStreamReader(is, "utf-8"));
            StringBuilder sb = new StringBuilder();
            sb.append(br.readLine());
            if (sb.toString().equals("")) {
                log.error("LQDBC驱动返回Null！");
            }
            obj = JSONObject.parseObject(sb.toString());
            if (obj.getInteger("code") == 0) {
                j = obj.getJSONArray("data");
            } else {
                log.error(obj);
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error(e(e));
        } finally {
            try {
                br.close();
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                is.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                os.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                pw.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                socket.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return j;
    }
	
	public static JSONObject queryAccessByObject(String sql,String path,String pwd) {
		return accessByObject(sql, path, pwd, "");
	}
	public static JSONObject accessByObject(String sql,String path,String pwd,String json) {
		Socket socket = null;
        OutputStream os = null;
        PrintWriter pw = null;
        InputStream is = null;
        JSONObject obj = null;
        BufferedReader br = null;
        try {
            // 和服务器创建连接
            socket = new Socket("127.0.0.1", 8099);
            // 要发送给服务器的信息
            os = socket.getOutputStream();
            pw = new PrintWriter(new OutputStreamWriter(os, "utf-8"));
            // 从服务器接收的信息
            //如果是插入更新删除的话，拼上liuqingEdit
            String edit="";
            if(sql.toLowerCase().indexOf("insert into")!=-1 || sql.toLowerCase().indexOf("delete from ")!=-1 || sql.toLowerCase().indexOf("update ")!=-1) {
            	edit="liuqingEdit";
            }
            sql = sql + " "+edit+"liuqing13934664424&&&"+path+"&&&"+pwd+"&&&"+json+"&&&\r\n";
            pw.write(sql);
            pw.flush();
            is = socket.getInputStream();
            br = new BufferedReader(new InputStreamReader(is, "utf-8"));
            StringBuilder sb = new StringBuilder();
            sb.append(br.readLine());
            if (sb.toString().equals("")) {
                log.error("LQDBC驱动返回Null！");
            }
            obj = JSONObject.parseObject(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e(e));
        } finally {
            try {
                br.close();
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                is.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                os.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                pw.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                socket.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return obj;
	}
	
	public static JSONArray accessExecute(String sql,String path,String pwd,JSONArray objs) {
		JSONObject obj = accessByObject(sql, path, pwd,objs.toJSONString());
        JSONArray j = null;
        try {
            if (obj.getInteger("code") == 0) {
                j = obj.getJSONArray("data");
            } else {
                log.error(obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e(e));
        } finally {
            
        }
        return j;
	}
	public static JSONArray query(String sql,String path,String pwd) {
		
        JSONObject obj = accessByObject(sql, path, pwd,"");
        JSONArray j = null;
        try {
            if (obj.getInteger("code") == 0) {
                j = obj.getJSONArray("data");
            } else {
                log.error(obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e(e));
        } finally {
            
        }
        return j;
    }
	
	public static String e(Exception e) {
		String str = e.toString() + "\r\n";
		for (int i = 0; i < e.getStackTrace().length; i++) {
			str += e.getStackTrace()[i] + "\r\n";
		}
		return str;
	}

}
